import time, json, os, django
# os.environ.setdefault("DJANGO_SETTINGS_MODULE", "get_weather.settings")  # project_name 项目名称
# django.setup()
from django.shortcuts import render
from templates.dataMysql import *
from django.http import HttpResponse
from templates.getTimeForecast import times
from templates.getTodayWeather import today_weather
from templates.dataMysql import querySave
from API_getWeather.models import todayDatas, hoursDatas
from templates.getSlefIp import get_host_ip

"""思路:1.获取请求的city_code,查询myslq有没有对应城市的
        2.存在,通过获取创建时间与现在时间进行相减;再判断,大于1小时就从新下载并保存,相反查询数据库信息
        3.不存在,直接下载保存"""


class allViews:
    def index(self, request):
        return HttpResponse('<h1>Please enter the true url...</h1> '
                            '<p>Example: 127.0.0.1:9999/searchCode/</p>')

    def search_code(self, request):
        # 这里是post请求
        cityName = request.POST.get('cityname')  # 获取前端输入内容
        code = queryCode().queryCityCode(cityName)
        ip = get_host_ip() # 获取本机ip
        if code:
            contexts = {
                'city_code': '{} -- {}'.format(cityName, code),
                'code':code,
                'ip':ip,
            }
            return render(request, 'searchCode.html', context=contexts)
        else:
            contexts = {
                'city_code': '{} -- {}'.format(cityName, code),
                'code': '查询的地址不存在,请重新输入对应的市/区',
                'ip': ip,
            }
            return render(request, 'searchCode.html', context=contexts)

    def get_todayWeather(self, request):  # 获取今天的数据
        city_code = request.GET.get('cityCode')
        create_time = querySave().queryCreateTimeByToday(city_code)
        if create_time is not None:  # 判断是否存在数据
            timeArray = time.strptime(str(create_time).split('.')[0],
                                      "%Y-%m-%d %H:%M:%S")  # 转为时间数组    由于create_time是毫秒级 create_time.split('.')[0] 将毫秒去掉
            timeStamp = time.mktime(timeArray)
            current_time = time.time()
            time_difference = current_time - timeStamp
            if time_difference > 3580:  # 通过判断时间差大于一小时就从新爬取并保存,否则直接查询
                result = today_weather().start(city_code)
                mysql_datas = todayDatas(city_code=result['cityCode'], city_name=result['cityName'],
                                         datas=result['contents'])
                mysql_datas.save()
                responses = {"error": 0, "status": "success", "result": result}
                return HttpResponse(json.dumps(responses, ensure_ascii=False),
                                    content_type="application/json, charset=utf-8")
            else:
                contents = querySave().queryContentsByToday(city_code)
                responses = {"error": 0, "status": "success", "result": contents}
                return HttpResponse(json.dumps(responses, ensure_ascii=False),
                                    content_type="application/json, charset=utf-8")
        else:
            result = today_weather().start(city_code)
            mysql_datas = todayDatas(city_code=result['cityCode'], city_name=result['cityName'],
                                     datas=result['contents'])
            mysql_datas.save()
            responses = {"error": 0, "status": "success", "result": result}
            return HttpResponse(json.dumps(responses, ensure_ascii=False),
                                content_type="application/json, charset=utf-8")

    def get_timesForecast(self, request):  # 获取7天的时间
        code = request.GET.get('cityCode')
        contents = times().start(code)
        responses = {"error": 0, "status": "success", "result": contents}
        return HttpResponse(json.dumps(responses, ensure_ascii=False),
                            content_type="application/json, charset=utf-8")

    def get_houlryWeather(self, request):  # 获取整点天气
        city_code = request.GET.get('cityCode')
        create_time = querySave().queryCreateTimeByHours(city_code)
        # print('城市 code:' + city_code)
        if create_time is not None:  # 判断是否存在数据
            timeArray = time.strptime(str(create_time).split('.')[0],
                                      "%Y-%m-%d %H:%M:%S")  # 转为时间数组    由于create_time是毫秒级 create_time.split('.')[0] 将毫秒去掉
            timeStamp = time.mktime(timeArray)
            current_time = time.time()
            time_difference = current_time - timeStamp
            if time_difference > 3600:  # 通过判断时间差大于一小时就从新爬取并保存,否则直接查询
                result = Hourly_weather().start(city_code)
                mysql_datas = hoursDatas(city_code=result['cityCode'], city_name=result['address'],
                                         aqi=result['hourAQI'], temperature=result['hourTe'],
                                         humidity=result['hourHu'], wind=result['hourWind'])
                mysql_datas.save()
                responses = {"error": 0, "status": "success", "result": result}
                return HttpResponse(json.dumps(responses, ensure_ascii=False),
                                    content_type="application/json, charset=utf-8")
            else:
                contents = querySave().queryContentsByHours(city_code)
                responses = {"error": 0, "status": "success", "result": contents}
                return HttpResponse(json.dumps(responses, ensure_ascii=False),
                                    content_type="application/json, charset=utf-8")
        else:
            result = Hourly_weather().start(city_code)
            mysql_datas = hoursDatas(city_code=result['cityCode'], city_name=result['address'], aqi=result['hourAQI'],
                                     temperature=result['hourTe'],
                                     humidity=result['hourHu'], wind=result['hourWind'])
            mysql_datas.save()
            responses = {"error": 0, "status": "success", "result": result}
            return HttpResponse(json.dumps(responses, ensure_ascii=False),
                                content_type="application/json, charset=utf-8")


if __name__ == '__main__':
    pass
